package com.btex.app.treaty;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.btex.app.Config;
import com.btex.app.R;
import com.btex.app.WebActivity;
import com.btex.app.entity.MyInfoListInfo;
import com.btex.app.pager.BaseFragment;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/26
 * @time 下午11:05
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */


//合约资产

public class ContractAssetsFragment extends BaseFragment {


    @BindView(R.id.fragment_contract_assets_recy)
    RecyclerView mFragmentContractAssetsRecy;
    Unbinder unbinder;
    @BindView(R.id.fragment_contract_assets_btc)
    TextView mFragmentContractAssetsBtc;
    @BindView(R.id.fragment_contract_assets_zhehe)
    TextView mFragmentContractAssetsZhehe;
    @BindView(R.id.treaty_behavior_tv_change)
    TextView mTreatyBehaviorTvChange;
    @BindView(R.id.fragment_bibi_swiperefreshLayout)
    SwipeRefreshLayout mFragmentBibiSwiperefreshLayout;
    @BindView(R.id.fragment_yinchang_imag)
    ImageView mFragmentYinchangImag;
    @BindView(R.id.fragment_yinchang_lin)
    LinearLayout mFragmentYinchangLin;
    private ContractAssetsAdapter mContractAssetsAdapter;

    private boolean isShow = false;
    private List<MyInfoListInfo.DataBean.CoinsBean> mCoins;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_contract_assets, null);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecy();
        getInfo();
        initListener();

    }

    private void initListener() {


        mFragmentYinchangLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isShow = !isShow;
                if (isShow) {

                    restRecy(isShow);

                    mFragmentYinchangImag.setBackground(getResources().getDrawable(R.mipmap.bibi_yc));
                } else {
                    restRecy(isShow);
                    mFragmentYinchangImag.setBackground(getResources().getDrawable(R.mipmap.rectangle));
                }

            }
        });


        if (mFragmentBibiSwiperefreshLayout != null) {

            mFragmentBibiSwiperefreshLayout.setRefreshing(true);
            mFragmentBibiSwiperefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getInfo();
                }
            });
        }

        mContractAssetsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                MyInfoListInfo.DataBean.CoinsBean o = (MyInfoListInfo.DataBean.CoinsBean) adapter.getData().get(position);
                String type = o.getType();

                switch (view.getId()) {
                    case R.id.item_trade_list_zhuan_ru:

                        Intent intent = new Intent(getActivity(), WebActivity.class);
                        intent.putExtra("web_url", Config.URL + "home/deposit/" + type);
                        startActivity(intent);
                        break;

                    case R.id.item_trade_list_zhuan_chu:
                        Intent i = new Intent(getActivity(), WebActivity.class);
                        i.putExtra("web_url", Config.URL + "home/withdraw/" + type);
                        startActivity(i);
                        break;
                }
            }
        });
        mTreatyBehaviorTvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MoneyTransfersActivity.class).putExtra("mSettle_anchor", "BTC"));
            }
        });
    }

    private void restRecy(boolean isShow) {


        if (mCoins != null) {

            List<MyInfoListInfo.DataBean.CoinsBean> coinsBeen = new ArrayList<>();

            for (int i = 0; i < mCoins.size(); i++) {
                String balance = mCoins.get(i).getBalance();
                if (Double.valueOf(balance) > 0) {
                    coinsBeen.add(mCoins.get(i));
                }

            }


            if (isShow) {

                if (mContractAssetsAdapter != null && mFragmentContractAssetsRecy != null) {
                    mContractAssetsAdapter.setType("1");
                    mContractAssetsAdapter.setNewData(coinsBeen);
                    mFragmentContractAssetsRecy.setAdapter(mContractAssetsAdapter);

                }
            } else {

                if (mContractAssetsAdapter != null && mFragmentContractAssetsRecy != null) {
                    mContractAssetsAdapter.setType("0");
                    mContractAssetsAdapter.setNewData(mCoins);
                    mFragmentContractAssetsRecy.setAdapter(mContractAssetsAdapter);
                }
            }

        }

    }

    private void getInfo() {
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.URL_MY_COINS + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();

                Log.i("jehfwefwu", result);
                if (mFragmentBibiSwiperefreshLayout != null) {
                    mFragmentBibiSwiperefreshLayout.setRefreshing(false);
                }

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {

                        Gson gson = new Gson();
                        MyInfoListInfo myInfoListInfo = gson.fromJson(result, MyInfoListInfo.class);
                        mCoins = myInfoListInfo.getData().getCoins();

                        mFragmentContractAssetsBtc.setText(myInfoListInfo.getData().getTotal_guzhi_BTC());
                        mFragmentContractAssetsZhehe.setText(myInfoListInfo.getData().getTotal_guzhi_CNY() + "\t" + "CNY");

                        if (mContractAssetsAdapter != null && mFragmentContractAssetsRecy != null) {
                            mContractAssetsAdapter.setNewData(mCoins);
                            mFragmentContractAssetsRecy.setAdapter(mContractAssetsAdapter);
                            restRecy(isShow);
                        }

                    } else {

                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });


//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.URL_MY_COINS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                Log.i("jehfwefwu", responseInfo.result);
//                if (mFragmentBibiSwiperefreshLayout != null) {
//                    mFragmentBibiSwiperefreshLayout.setRefreshing(false);
//                }
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//
//                        Gson gson = new Gson();
//                        MyInfoListInfo myInfoListInfo = gson.fromJson(responseInfo.result, MyInfoListInfo.class);
//                        mCoins = myInfoListInfo.getData().getCoins();
//
//                        mFragmentContractAssetsBtc.setText(myInfoListInfo.getData().getTotal_guzhi_BTC());
//                        mFragmentContractAssetsZhehe.setText(myInfoListInfo.getData().getTotal_guzhi_CNY() + "\t" + "CNY");
//
//                        if (mContractAssetsAdapter != null && mFragmentContractAssetsRecy != null) {
//                            mContractAssetsAdapter.setNewData(mCoins);
//                            mFragmentContractAssetsRecy.setAdapter(mContractAssetsAdapter);
//                            restRecy(isShow);
//                        }
//
//
//                    } else {
//
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });

    }

    private void initRecy() {

        if (mFragmentContractAssetsRecy != null) {
            mFragmentContractAssetsRecy.setLayoutManager(new LinearLayoutManager(getActivity()));
            mContractAssetsAdapter = new ContractAssetsAdapter();
        }


    }

    @Override
    public void setData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.i("weifweufhiweufhw", "2");
        if (isVisibleToUser) {
//            initRecy();
//            getInfo();
//            initListener();
            getInfo();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        getInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void CoinsFragment(String messageEvent) {

        if (messageEvent.equals("loginsuccess")) {
            Log.i("wehfowiefwhefo", "2222222222222222");
            getInfo();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
